package top.likeqc.blog.web.admin;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import top.likeqc.blog.pojo.User;
import top.likeqc.blog.service.UserService;

import javax.servlet.http.HttpSession;

/**
 * @author likeqc.top
 * @date 2021/4/16 14:14
 */
@Controller
@RequestMapping("/admin")
public class LoginController {

    @Autowired private UserService userService;

    /**
     * 放回后台时直达登陆页面登陆页面
     * @return 登陆页面
     */
    @GetMapping
    public String loginPage() {
        System.out.println("后台登陆页面。。。。");
        return "admin/login";
    }

    /**
     * 登陆
     * @param username 用户名
     * @param password 密码
     * @return 成功：首页，失败：登陆页面
     */
    @PostMapping("/login")
    public String login(@RequestParam String username,
                        @RequestParam String password,
                        HttpSession session,
                        RedirectAttributes attributes) {
        System.out.println("username:" + username + ", password:" + password);
        User user = userService.checkUser(username, password);
        System.out.println(user);
        if (user != null) {
            user.setPassword(null);
            session.setAttribute("user", user);
            return "/admin/index";
        } else {
            attributes.addFlashAttribute("message", "用户名和密码错误！");
            return "redirect:/admin";
        }
    }

    /**
     * 登出
     * @return 登陆页面
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/admin";
    }
}
